import React, { useEffect, useState, useRef, useMemo } from 'react';
import { NavigationProp, RouteProp, StackActions } from '@react-navigation/native';
import { StyleSheet, TouchableOpacity, View, Text, Image, TextInput, Button, Alert, TouchableHighlight, Dimensions } from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { useSelector } from 'react-redux';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import AntDesign from 'react-native-vector-icons/AntDesign';
import FontAwesome5 from 'react-native-vector-icons/AntDesign';
import HomeRequest from '../../../request/homeRequest.ts';
import CustomFlatList from '../../../component/CustomFlatList.tsx';
import { useReactive } from 'ahooks';
import Picker from '../../../component/Picker.tsx';
import { Badge, Actionsheet, useDisclose, Stack, Center, ScrollView, Input, Icon } from 'native-base';
import { ShowConfirmDialog } from '../../../component/ConfirmDialog.tsx';
import { EAlarmType, ENotifyState } from '../../../common/enum.ts';
import { useToast } from 'react-native-toast-notifications';
import Tools from '../../../utils/Tools.ts';
import DatePicker from '../../../component/DatePicker.tsx';

interface IInformListProps {
  navigation: NavigationProp<any, 'informList'>;
  route: RouteProp<{ informList: any }, 'informList'>;
  onChange: (text: string) => void;
}

interface IData {
  notifyState: number | string;
  notifyType: string | number;
  beginTime: string;
  endTime: string;
  address: string;
  pageNo: number;
  total: number;
  pickerType: string;
  pickerCommunityShow: boolean;
  stateList: { text: string; value: number }[];
  typeList: { text: string; value: string }[];
  currentDate?: { date: string[]; time: string[] };
  year: number;
  month: string | number;
  date: string | number;
  timeSelect: number;
  refreshing: boolean;
  isLoading: boolean;
  notifyList: IGetNotifyDetail[];
}

const wHeight = Dimensions.get('window').height;

const InformList: React.FC<IInformListProps> = ({ navigation, route, onChange }) => {
  const { isOpen, onOpen, onClose } = useDisclose();
  const [isModalVisible, setModalVisible] = useState(false);
  const data = useReactive<IData>({
    notifyState: '',
    notifyType: '',
    beginTime: '',
    endTime: '',
    address: '',
    pageNo: 1,
    total: 1,
    pickerCommunityShow: false,
    pickerType: 'state',
    timeSelect: 1,
    stateList: [
      { text: '通知中', value: 1 },
      { text: '通知成功', value: 10 },
      { text: '通知失败', value: -1 },
      { text: '部分成功', value: 5 },
    ],
    typeList: [],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    date: new Date().getDate(),
    notifyList: [],
    refreshing: false,
    isLoading: false,
  });

  const beeperId = useSelector((state: RootState) => state.beeperId);

  const getDateStr = (year: number, month: string, date: string): string => {
    return `${year}-${month}-${date}`;
  };

  useEffect(() => {
    data.typeList = Object.entries(EAlarmType).map(([value, text]) => ({
      text,
      value: value as EAlarmType,
    }));
  }, []);

  const getNotifyLists = () => {
    Loading.show('正在加载中');
    if (data.pageNo <= data.total) {
      data.isLoading = true;
      let params = {
        pageNo: data.pageNo,
        pageSize: 20,
        beeperId,
        beginTime: data.beginTime,
        endTime: data.endTime,
        notifyState: data.notifyState,
        notifyType: data.notifyType,
        address: data.address,
      };
      HomeRequest.GetNotifyList(params)
        .then((res) => {
          Loading.hide();
          data.notifyList = [...data.notifyList, ...res.data.list];
          data.total = res.data.totalPage;
          data.pageNo += 1;
          data.isLoading = false;
          data.refreshing = false;
        })
        .catch((err) => {
          Loading.hide();
          data.isLoading = false;
          data.refreshing = false;
        });
    } else {
      Loading.hide();
    }
  };

  const customListRefresh = () => {
    data.refreshing = true;
    data.pageNo = 1;
    data.total = 1;
    data.notifyList = [];
    getNotifyLists();
  };

  const renderItem = (item: IGetNotifyDetail, index: number) => {
    return (
      <TouchableOpacity
        style={styles.infoView}
        onPress={() => {
          const pushAction = StackActions.push('informDetails', { notifyId: item.notifyId });
          navigation.dispatch(pushAction);
        }}
      >
        <View style={styles.infoChild}>
          <Text style={{ color: '#000' }}>事故发生地：{item.address}</Text>
        </View>
        <View style={styles.infoChild}>
          <Text style={{ color: '#000' }}>事故类型：{EAlarmType[item.notifyType as keyof typeof EAlarmType]}</Text>
        </View>
        <View style={styles.infoChild}>
          <Text style={{ color: '#000' }}>发生时间：{item.createDate}</Text>
        </View>
        <View style={styles.infoBadge}>
          {item.notifyState === 1 && (
            <Badge colorScheme="info" alignSelf="flex-start" variant={'solid'}>
              通知中
            </Badge>
          )}
          {item.notifyState === 10 && (
            <Badge colorScheme="success" alignSelf="flex-start" variant={'solid'}>
              通知成功
            </Badge>
          )}
          {item.notifyState === -1 && (
            <Badge colorScheme="error" alignSelf="flex-start" variant={'solid'}>
              通知失败
            </Badge>
          )}
          {item.notifyState === 5 && (
            <Badge colorScheme="warning" alignSelf="flex-start" variant={'solid'}>
              部分成功
            </Badge>
          )}
        </View>
      </TouchableOpacity>
    );
  };

  /**
   * 选择器确认
   * @param result
   */
  const handlePickerConfirm = (result: { names: string; values: Array<string | number> }) => {
    switch (data.pickerType) {
      case 'type':
        data.notifyType = result.values[0];
        break;

      case 'state':
        data.notifyState = result.values[0];
        break;
    }
    data.pickerCommunityShow = false;
  };

  const [viewHeight, setViewHeight] = useState(0);

  const viewLayout = (event: any) => {
    let { x, y, width, height } = event.nativeEvent.layout;
    setViewHeight(height);
  };

  return (
    <View style={styles.viewBox}>
      <View
        style={styles.searchView}
        onLayout={(e) => {
          viewLayout(e);
        }}
      >
        <View style={styles.comView}>
          <View style={styles.cLeft}>
            <Text style={{ color: '#000' }}>通知状态</Text>
          </View>
          <View style={styles.cRight}>
            <TouchableOpacity
              style={styles.selectView}
              onPress={() => {
                (data.pickerCommunityShow = true), (data.pickerType = 'state');
              }}
            >
              <Text style={{ color: '#000' }}>{data.notifyState ? ENotifyState[data.notifyState as number] : '请选择通知状态'}</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View style={styles.comView}>
          <View style={styles.cLeft}>
            <Text style={{ color: '#000' }}>事故类型</Text>
          </View>
          <View style={styles.cRight}>
            <TouchableOpacity
              style={styles.selectView}
              onPress={() => {
                (data.pickerCommunityShow = true), (data.pickerType = 'type');
              }}
            >
              <Text style={{ color: '#000' }}>{data.notifyType ? EAlarmType[data.notifyType as keyof typeof EAlarmType] : '请选择事故类型'}</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View style={styles.comView}>
          <View style={styles.cLeft}>
            <Text style={{ color: '#000' }}>发生时间</Text>
          </View>
          <View style={styles.cRight2}>
            <View style={{ width: '40%' }}>
              <TouchableOpacity
                style={styles.selectView}
                onPress={() => {
                  setModalVisible(true);
                  data.timeSelect = 1;
                }}
              >
                <Text style={{ color: '#000' }}>{data.beginTime ? data.beginTime : '开始时间'}</Text>
              </TouchableOpacity>
            </View>
            <View style={{ width: '10%', alignItems: 'center' }}>
              <Text> — </Text>
            </View>
            <View style={{ width: '40%' }}>
              <TouchableOpacity
                style={styles.selectView}
                onPress={() => {
                  setModalVisible(true);
                  data.timeSelect = 2;
                }}
              >
                <Text style={{ color: '#000' }}>{data.endTime ? data.endTime : '结束时间'}</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
        <View style={styles.comView}>
          <View style={styles.cLeft}>
            <Text style={{ color: '#000' }}>事故发生地</Text>
          </View>
          <View style={styles.cRight}>
            <Input
              onChangeText={(e) => {
                data.address = e;
              }}
              value={data.address}
              size="md"
              height={10}
              InputLeftElement={<Icon as={<MaterialIcons name="search" />} size={6} ml="2" color="#aaa" />}
              placeholder="请输入事故发生地"
            />
          </View>
        </View>
        <View style={styles.btnView}>
          <TouchableOpacity
            style={styles.btn1}
            onPress={() => {
              data.pageNo = 1;
              data.notifyList = [];
              getNotifyLists();
            }}
          >
            <Text style={{ color: '#fff' }}>查询</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.btn2}
            onPress={() => {
              data.address = '';
              data.beginTime = '';
              data.endTime = '';
              data.notifyState = '';
              data.notifyType = '';
              data.pageNo = 1;
              data.notifyList = [];
              getNotifyLists();
            }}
          >
            <Text style={{ color: '#000' }}>重置</Text>
          </TouchableOpacity>
        </View>
      </View>
      <View style={[styles.listView, { height: wHeight - viewHeight - 80 }]}>
        <CustomFlatList data={data.notifyList} renderItem={({ item, index }) => renderItem(item, index)} refreshing={data.refreshing} isLoading={data.isLoading} onEndReached={getNotifyLists} onRefresh={customListRefresh}></CustomFlatList>
      </View>
      <Picker visible={data.pickerCommunityShow} data={data.pickerType === 'state' ? [data.stateList] : [data.typeList]} onConfirm={handlePickerConfirm} onCancel={() => (data.pickerCommunityShow = false)} title={data.pickerType === 'state' ? '选择通知状态' : '选择事故类型'} onChange={() => (data.pickerCommunityShow = false)} />
      <DatePicker
        show={isModalVisible}
        currentDate={[data.year, data.month, data.date]}
        columnsType={['year', 'month', 'day']}
        minDate={`2019,01,01`}
        maxDate={`${new Date().getFullYear()},${new Date().getMonth() + 1},${new Date().getDate() + 1}`}
        closeOnClickOverlay
        onClose={() => setModalVisible(false)}
        onConfirm={(date) => {
          data.year = Number(date[0]);
          data.month = date[1];
          data.date = date[2];
          if (data.timeSelect === 1) {
            data.beginTime = getDateStr(data.year, data.month, data.date);
          } else {
            data.endTime = getDateStr(data.year, data.month, data.date);
          }
          setModalVisible(false);
        }}
        title={'选择时间'}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  viewBox: {
    padding: 12,
    height: '100%',
  },
  searchView: {
    borderRadius: 8,
    backgroundColor: '#fff',
    padding: 10,
  },
  listView: {
    marginVertical: 20,
  },
  comView: {
    marginBottom: 10,
    flexDirection: 'row',
    alignItems: 'center',
  },
  cLeft: {
    width: '25%',
  },
  cRight: {
    flex: 2,
  },
  cRight2: {
    flex: 2,
    flexDirection: 'row',
    alignItems: 'center',
  },
  selectView: {
    maxWidth: 140,
    borderWidth: 1,
    borderColor: '#ddd',
    paddingHorizontal: 10,
    paddingVertical: 6,
    alignItems: 'center',
  },
  btnView: {
    flexDirection: 'row',
  },
  btn1: {
    flex: 1,
    backgroundColor: CommonStyle.mainColor,
    alignItems: 'center',
    height: 34,
    justifyContent: 'center',
    marginHorizontal: 10,
  },
  btn2: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#ccc',
    alignItems: 'center',
    height: 34,
    justifyContent: 'center',
    marginHorizontal: 10,
  },
  infoView: {
    backgroundColor: '#fff',
    marginBottom: 20,
    padding: 10,
    borderRadius: 8,
  },
  infoChild: {
    marginBottom: 12,
  },
  infoBadge: {
    position: 'absolute',
    right: 10,
    top: 10,
  },
});

export default InformList;
